<script lang="ts" setup name="PhyDetailedStatistics">
import {PageConfig, defaultPage, defaultPageSize, defaultPageSizes, defaultLayout} from '@/components/dTable/dFooter'
import {OperButton, SearchFromItem} from '@/components/dTable/dHeader'
import {HeaderData, RowOperbuttons} from '@/components/dTable/dTable'
import pageContainer from '@/components/pageContainer.vue'
import dTablePromote from '@/components/dTable/dTablePromote.vue'
import {ElMessage, FormRules} from 'element-plus/es'
import {onActivated, reactive, ref} from 'vue'
import {checkIsJSON, downFile, getYearMonthDayStr, NoNumber, Number_3, transfDicArrData} from '@/util/common'
import {getDiagnosticTable, DiagnosticTableParams} from '@/api/medicalExaminerDesk/medicalExaminerDesk'
import {SeleteData} from '@/api/config'
import dayjs from 'dayjs'
import {getTeamListAll, SelectTeamLsit} from '@/api/publicHealthExamination/communitySettings'
import {getAllCategoryList} from '@/api/physicalExaminationManager/majorCategories'
import {getAllPackageList} from '@/api/publicHealthExamination/physicalExaminationRegister'
import useCommon from '@/store/common'
import {exportPhyDetailed, ExportPhyDetailed} from '@/api/statisticalAnalysis/phyDetailedStatistics'
const common = useCommon.setup().store

//显示加载状态
const showLoading = ref(false)

//当前页面 表格数据 定义
const tableData = ref<Array<RowOperbuttons>>([])
// 体检套餐下拉
const packageList = ref<Array<SeleteData>>([])
// 社区下拉
const selectTeamLsit = ref<Array<SelectTeamLsit>>([])
// 体检状态下拉
const selectRegisterStatus = ref<Array<SeleteData>>([])
// 性别下拉
const selectGanderList = ref<Array<SeleteData>>([
  {label: '男', value: '男'},
  {label: '女', value: '女'}
])
// 是否异常下拉
const selectAbnormalList = ref<Array<SeleteData>>([
  {label: '是', value: '0'},
  {label: '否', value: '1'}
])
// 体检大类下拉
const selectCheckupCategory = ref<Array<SeleteData>>([])

//表格头部数据定义
const tableHeaderData = ref<Array<HeaderData>>([
  {prop: 'phyDate', label: '体检日期', columnType: 'text', 'min-width': '100', fixed: 'left'},
  {prop: 'checkupNo', label: '体检号', columnType: 'text', 'min-width': '100', fixed: 'left'},
  {prop: 'personName', label: '姓名', columnType: 'text', 'min-width': '100', fixed: 'left'},
  {prop: 'idNo', label: '身份证', columnType: 'text', 'min-width': '100'},
  {prop: 'gender', label: '性别', columnType: 'text', 'min-width': '100'},
  {prop: 'age', label: '年龄', columnType: 'text', 'min-width': '100'},
  {prop: 'phone', label: '联系电话', columnType: 'text', 'min-width': '100'},
  {prop: 'teamName', label: '社区', columnType: 'text', 'min-width': '100'},
  {prop: 'address', label: '居住地址', columnType: 'text', 'min-width': '100'},
  {prop: 'phyDate', label: '中医体质辨识', columnType: 'text', width: '130'},
  {prop: 'notTestCategory', label: '症状', columnType: 'text', 'min-width': '100'},
  {prop: 'registerStatusName', label: '体温', columnType: 'text', 'min-width': '100'}
])

//搜索项数据定义
const searchFromItems = ref<Array<SearchFromItem>>([
  {label: '体检套餐', placeholder: '请选择体检套餐', prop: 'packageId', type: 'selete', seleteData: packageList.value, changeSubmit: true, filterable: true, notClearable: true},
  {
    label: '体检日期',
    placeholder: ['开始时间', '结束时间'],
    type: 'antdRange',
    prop: 'phyDate',
    showTime: false,
    changeSubmit: true,
    notClearable: true,
    dateFormat: 'YYYY-MM-DD',
    style: {width: '310px'}
  },
  {label: '姓名', placeholder: '请输入姓名', prop: 'personName', type: 'input', enterSubmit: true},
  {label: '性别', placeholder: '请选择性别', prop: 'gander', type: 'selete', seleteData: selectGanderList.value, changeSubmit: true, filterable: true},
  {label: '年龄段', placeholder: '请输入年龄段', prop: 'ageStage', type: 'slot', slotName: 'ageStage'},
  {label: '社区', placeholder: '请选择社区', prop: 'teamId', type: 'selete', seleteData: selectTeamLsit.value, changeSubmit: true, filterable: true},
  {label: '体检状态', placeholder: '请选择体检状态', prop: 'registerStatus', type: 'selete', seleteData: selectRegisterStatus.value, changeSubmit: true, filterable: true},
  {label: '体检大类', placeholder: '请选择体检大类', prop: 'notTestCategoryIdsArr', type: 'selete', seleteData: selectCheckupCategory.value, changeSubmit: true, filterable: true},
  {label: '是否异常', placeholder: '请选择是否异常', prop: 'abnormal', type: 'selete', seleteData: selectAbnormalList.value, changeSubmit: true, filterable: true}
])

// 表格筛选参数
const searchFromData = reactive<DiagnosticTableParams & ExportPhyDetailed>({
  phyDate: [dayjs().startOf('month').format('YYYY-MM-DD'), getYearMonthDayStr(Date.now())],
  packageId: ''
})

//判断年龄
const ageStage = (_rule, _value: string, callback) => {
  if (!searchFromData.minAge && !searchFromData.maxAge) {
    callback()
    return
  }
  const vLeft = searchFromData.minAge
  const vRight = searchFromData.maxAge
  if (vLeft && !Number_3.test(searchFromData.minAge || '')) {
    callback(new Error('不超过3位的正整数!'))
  } else if (vRight && !Number_3.test(searchFromData.maxAge || '')) {
    callback(new Error('不超过3位的正整数!'))
  } else {
    callback()
  }
}

// 判断年龄前后大小
const ageStageBigger = (_rule, _value: string, callback) => {
  const vLeft = searchFromData.minAge
  const vRight = searchFromData.maxAge
  if (vLeft && vRight && Number(vLeft) > Number(vRight)) {
    return callback(new Error('起始值应小于结束值'))
  } else {
    return callback()
  }
}

const searchFromRules = reactive<FormRules>({
  ageStage: [
    {validator: ageStage, trigger: ['change', 'blur']},
    {validator: ageStageBigger, trigger: ['change', 'blur']}
  ],
  personName: [
    {
      message: '长度应不超过20个字符',
      max: 20,
      trigger: ['change', 'blur']
    },
    {
      message: '请输入汉字、字母、字符',
      pattern: NoNumber,
      trigger: ['change', 'blur']
    }
  ]
})

//表头按钮
const operButtons = ref<Array<OperButton>>([
  {
    label: '导出Excel',
    type: 'noraml',
    iconConfig: {icon: 'common-import', type: 'custom'},
    code: 'export'
  }
])

//分页配置
const pageConfig = reactive<PageConfig>({
  currentPage: defaultPage,
  pageSize: defaultPageSize,
  pageSizes: defaultPageSizes,
  total: 0,
  disabled: false,
  layout: defaultLayout
})

/**
 * @description: 查询表格数据
 * @param {*} resetPage 重置页码
 * @return {*}
 */
const searchData = (resetPage?: boolean) => {
  showLoading.value = true
  if (resetPage) pageConfig.currentPage = 1
  //输入一个年龄补全另一个年龄
  if (searchFromData.minAge && !searchFromData.maxAge) {
    searchFromData.maxAge = searchFromData.minAge
  }
  if (!searchFromData.minAge && searchFromData.maxAge) {
    searchFromData.minAge = searchFromData.maxAge
  }
  // 请求参数
  const params: DiagnosticTableParams = {
    ...searchFromData
  }
  params.page = pageConfig.currentPage
  params.limit = pageConfig.pageSize
  searchFromData.phyDate?.length ? (params.startDate = searchFromData.phyDate[0] + ' 00:00:00') : delete params.startDate
  searchFromData.phyDate?.length ? (params.endDate = searchFromData.phyDate[1] + ' 23:59:59') : delete params.endDate
  delete params.phyDate
  getDiagnosticTable(params)
    .then((res) => {
      const {data} = res.data
      tableData.value = data.records
      pageConfig.total = data.total === null ? 0 : data.total
    })
    .catch((err) => {
      console.warn(err)
    })
    .finally(() => {
      showLoading.value = false
    })
}

//搜索事件
const onSubmit = () => {
  searchData(true)
}

//清除搜索栏数据事件
const clearForm = () => {
  delete searchFromData.minAge
  delete searchFromData.maxAge
  searchFromData.phyDate = [dayjs().startOf('month').format('YYYY-MM-DD'), getYearMonthDayStr(Date.now())]
  searchData(true)
}

//清空搜索表单事件
const onFormClear = () => {
  clearForm()
}

//分页尺寸改变事件
const onSizeChange = () => {
  searchData(true)
}

//当前页改变事件
const onCurrentChange = () => {
  searchData()
}

//操作按钮事件
const onOperation = (name: string) => {
  if (name === 'export') {
    // if (tableData.value.length === 0) {
    //   ElMessage.warning('当前搜索条件下暂无数据导出！')
    //   return
    // }
    // 请求参数
    // const params: DiagnosticTableParams = {
    //   ...searchFromData
    // }
    // searchFromData.phyDate?.length ? (params.startTime = searchFromData.phyDate[0] + ' 00:00:00') : delete params.startTime
    // searchFromData.phyDate?.length ? (params.endTime = searchFromData.phyDate[1] + ' 23:59:59') : delete params.endTime
    // delete params.phyDate
    // delete params.page
    // delete params.limit
    const params: ExportPhyDetailed = {
      packageId: searchFromData.packageId
    }
    exportPhyDetailed(params).then((res) => {
      const enc = new TextDecoder('utf-8')
      const resStr = enc.decode(new Uint8Array(res.data))
      if (checkIsJSON(resStr)) {
        const data = JSON.parse(resStr)
        if (data?.code !== 200 || !data?.success) {
          ElMessage.error(data?.msg || '未知错误')
        } else {
          data?.msg && ElMessage.warning(data?.msg)
        }
      } else {
        downFile('体检明细统计.xlsx', res.data)
        ElMessage.success('体检明细统计导出成功!')
      }
    })
  }
}

/**
 * @description: 获取字典值
 * @return {*}
 */
const getDict = () => {
  selectRegisterStatus.value.length = 0
  common
    .getDicData('physical_examination')
    .then((res) => {
      const arr: Array<SeleteData> = transfDicArrData(res)
      arr.forEach((item) => {
        selectRegisterStatus.value.push(item)
      })
    })
    .finally(() => {
      searchData() // 列表数据
    })
}

/**
 * @description: 获取体检套餐下拉
 * @return {*}
 */
const getPackageSelect = () => {
  packageList.value.length = 0
  getAllPackageList()
    .then((res) => {
      const {data} = res.data
      data.length &&
        data.forEach((item) => {
          packageList.value.push({label: item.packageName, value: item.id || ''})
        })
      // !searchFromData.registerStatus && (searchFromData.registerStatus = selectRegisterStatus.value[0].value as number)
    })
    .finally(() => {
      searchData() // 列表数据
    })
}

/**
 * @description: 获取社区下拉
 * @return {*}
 */
const getTeamSelect = () => {
  selectTeamLsit.value.length = 0
  getTeamListAll().then((res) => {
    res.data.data?.length &&
      res.data.data.forEach((item) => {
        selectTeamLsit.value.push({label: item.name, value: item.id || '', address: `${item.regionName || ''}${item.address || ''}`})
      })
  })
}

/**
 * @description: 获取体检大类下拉
 * @return {*}
 */
const getCheckupCategoryList = () => {
  selectCheckupCategory.value.length = 0
  getAllCategoryList().then((res) => {
    const {data} = res.data
    data.length &&
      data.forEach((item) => {
        selectCheckupCategory.value.push({label: item.categoryName, value: item.categoryName || ''})
      })
  })
}

onActivated(() => {
  getDict() // 字典
  getPackageSelect() // 体检套餐下拉
  getTeamSelect() // 社区下拉
  getCheckupCategoryList() // 体检大类下拉
})
</script>
<template>
  <page-container>
    <d-table-promote
      :stripe="true"
      :show-loading="showLoading"
      :oper-buttons="operButtons"
      :table-data="tableData"
      :table-header-data="tableHeaderData"
      :page-config="pageConfig"
      :search-form-data="searchFromData"
      :search-rules="searchFromRules"
      :search-form-items="searchFromItems"
      search-from-justify="flexStart"
      @operation="onOperation"
      @form-submit="onSubmit"
      @form-clear="onFormClear"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
    >
      <template #ageStage>
        <div>
          <el-row :gutter="5">
            <el-col :span="11">
              <el-input v-model="searchFromData.minAge" clearable placeholder="最小年龄" label="" @keyup.enter="onSubmit" />
            </el-col>
            <el-col :span="2">
              ~
            </el-col>
            <el-col :span="11">
              <el-input v-model="searchFromData.maxAge" clearable placeholder="最大年龄" label="" @keyup.enter="onSubmit" />
            </el-col>
          </el-row>
        </div>
      </template>
    </d-table-promote>
  </page-container>
</template>
<style lang="less" scoped></style>
